﻿using AutoMapper;
using B.S.BaseData.Api.Write.Applicantion.Command.RBAC;
using B.S.BaseData.Api.Write.GetCelim;
using B.S.BaseData.ErrorCode;
using B.S.BaseData.Infrastructure.Interface;
using B.S.BataBase.Domain.RBAC;
using MediatR;
using System.Security.Claims;
using Yitter.IdGenerator;

namespace B.S.BaseData.Api.Write.Applicantion.CommandHandler.RBAC
{
    public class CreatePermissionHandler : IRequestHandler<CreatePermissionCommand, APIResult<int>>
    {
        private readonly IBaseRepository<PermissionsModel> permissionRepo;
        private readonly IMapper mapper;
        private readonly IIdContextCemil _idContextCemil;
        private readonly IHttpContextAccessor _contextAccessor;
        public CreatePermissionHandler(IBaseRepository<PermissionsModel> permissionRepo, IMapper mapper, IIdContextCemil idContextCemil, IHttpContextAccessor contextAccessor)
        {
            this.permissionRepo = permissionRepo;
            this.mapper = mapper;
            _idContextCemil = idContextCemil;
            _contextAccessor = contextAccessor;
        }

        public Task<APIResult<int>> Handle(CreatePermissionCommand request, CancellationToken cancellationToken)
        {
            APIResult<int> res = new APIResult<int>();
            var permission= permissionRepo.GetAll().Where(x=>x.PermissionsName==request.PermissionsName).FirstOrDefault();
            if (permission != null)
            {
                res.Code = ApiEnum.Fail;
                res.Msg = "你要添加的权限已存在";
                return Task.FromResult(res);
            }
            var model=mapper.Map<PermissionsModel>(request);
            model.Id=YitIdHelper.NextId();
            model.CreateTime=DateTime.Now;
            model.CreateName= _contextAccessor.HttpContext.User.FindFirstValue("UserName");
            var list=permissionRepo.CreateAsync(model).Result;
            if (list > 0)
            {
                res.Code = ApiEnum.Success;
                res.Msg = "添加成功";
                res.Data= list;
            }
            else
            {
                res.Code = ApiEnum.Fail;
                res.Msg = "添加失败";
                res.Data = list;
            }
            return Task.FromResult(res);
        }
    }
}
